package com.humble.vichatbackend.controller;

import com.humble.vichatbackend.common.BaseResponse;
import com.humble.vichatbackend.model.enums.ErrorCode;
import com.humble.vichatbackend.common.UserLoginRequest;
import com.humble.vichatbackend.common.UserRegisterRequest;
import com.humble.vichatbackend.constant.UserConstant;
import com.humble.vichatbackend.exception.BusinessException;
import com.humble.vichatbackend.model.domain.User;
import com.humble.vichatbackend.model.vo.UserVO;
import com.humble.vichatbackend.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.filter.RequestContextFilter;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import java.util.List;

import static org.apache.commons.lang3.math.NumberUtils.min;


@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name="用户接口列表")
public class UserController {
    @Resource
    UserService userService;
    @Autowired
    private RequestContextFilter requestContextFilter;

    @PostMapping("/register")
    @Operation(description="用户注册接口")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if(userRegisterRequest==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        String username = userRegisterRequest.getUsername();
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();

        if (StringUtils.isAnyBlank(username,userAccount,userPassword,checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long register = userService.register(userRegisterRequest);
        return BaseResponse.success(register,"注册成功！");
    }

    @PostMapping("/login")
    @Operation(description="用户登录接口")
    public BaseResponse<UserVO> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            return BaseResponse.fail(ErrorCode.PARAMS_ERROR);
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            return BaseResponse.fail(ErrorCode.PARAMS_ERROR);
        }
        UserVO user = userService.userLogin(userAccount, userPassword, request);
        return BaseResponse.success(user);
    }

    @PostMapping("/logout")
    @Operation(description="用户登出接口")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int result = userService.userLogout(request);
        return BaseResponse.success(result);
    }

    @GetMapping("/current")
    @Operation(description="获取当前用户接口")
    public BaseResponse<UserVO> getCurrentUser(HttpServletRequest request){
        UserVO current = (UserVO)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if(current==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return BaseResponse.success(current);
    }

    @GetMapping("/search")
    @Operation(description="查询用户接口")
    public BaseResponse<List<UserVO>> searchUsers(String username){
        if(username==null||StringUtils.isEmpty(username)){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        List<UserVO> userVOs = userService.searchUsers(username);
        return BaseResponse.success(userVOs);

    }

    @GetMapping("/search/tags")
    @Operation(description="根据标签查询用户接口")
    public BaseResponse<List<UserVO>> searchByTags(@RequestParam(required = false) List<String> tags){
        if(tags==null||tags.isEmpty()){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        List<UserVO> userVOs = userService.searchUserByTags(tags);
        return BaseResponse.success(userVOs);
    }

    @PostMapping("/update")
    @Operation(description="修改当前用户接口")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request){
        UserVO currentUser = (UserVO)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(currentUser.getUserAccount()==null){
            throw new BusinessException("登录信息存在异常!",50000,"");
        }
        if(currentUser.getUserAccount().equals(user.getUserAccount())&&currentUser.getUserRole()!=UserConstant.ADMIN_ROLE){
            log.info("用户越界修改其他用户信息，账号为：{}",currentUser.getUserAccount());
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Integer count = userService.updateUser(user, currentUser,request);
        if(count<0){
            return BaseResponse.fail(50000,"更新失败,系统内部异常");
        }
        return BaseResponse.success(count);
    }

    @PostMapping("/manager/update")
    @Operation(description="管理者修改用户接口")
    public BaseResponse<Integer> managerUpdateUser(@RequestBody User user, HttpServletRequest request){
        UserVO currentUser = (UserVO)request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if(currentUser==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(currentUser.getUserRole()!=UserConstant.ADMIN_ROLE){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        Integer count = userService.updateUser(user,currentUser,request);
        if(count<0){
            return BaseResponse.fail(50000,"更新失败,系统内部异常");
        }
        return BaseResponse.success(count);
    }

    @PostMapping("/delete")
    @Operation(description="删除用户接口")
    public BaseResponse<Boolean> deleteUser(Long id, HttpServletRequest request) {
        UserVO current = (UserVO) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        if(current==null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        if(current.getUserRole()!=UserConstant.ADMIN_ROLE){
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        if(id==null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        Integer count = userService.deleteUser(id);
        if(count<0){
            return BaseResponse.fail(50000,"删除失败");
        }
        if(count==0){
            return BaseResponse.success(true,"未找到匹配用户");
        }
        return BaseResponse.success(true,"删除成功");
    }

    @GetMapping("/recommend")
    @Operation(description="推荐用户接口")
    public BaseResponse<List<UserVO>> recommendUsers(HttpServletRequest request,int size){
        if(request==null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
        UserVO currentUser = (UserVO) request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        return BaseResponse.success(userService.getRecommendUser(currentUser,size));


    }

}
